package dang.interceptor;

import java.sql.Connection;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import dang.common.DBUtil;

public class TransactionInterceptor extends MethodFilterInterceptor {
	static{
		System.out.println("TransactionInterceptor");
	}
	private DBUtil dbUtil;
	public void setDbUtil(DBUtil dbUtil) {
		//可以注入，使用时却为空
		System.out.println("jjjjjjjjjjjjjjjjjjjjjj");
		System.out.println(dbUtil);
		this.dbUtil = dbUtil;
	}
	public DBUtil getDbUtil() {
		return dbUtil;
	}
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		System.out.println("bbbbbbbbbbbbbbb");
		System.out.println("doIntercept");
		
		DBUtil dbUtil=getDbUtil();
		System.out.println(dbUtil);
		Connection con = dbUtil.openInThread();
		System.out.println(con);
		con.setAutoCommit(false);
		try{
			String resultCode = invocation.invoke();//执行Action业务方法
			con.commit();
			return resultCode;
		}catch(Exception e){
			//TODO 记录异常信息,写入日志文件
			e.printStackTrace();
			con.rollback();
			return "error";
		}finally{
			dbUtil.closeInThread();
		}
	}

}
